package testJdk.net.testTcp;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author keyer
 * @Name : learn_jdk.net.testTcp.TCPServerDemo
 * @Description : 描述
 * Created by cyd on 2021-07-15 15:10:55
 */
public class TcpServerDemo {
    private ServerSocket serverSocket;
    private DataInputStream dataInputStream;

    public void startServer() {
        Socket socket = null;
        try {
            serverSocket = new ServerSocket(10003);
            socket = serverSocket.accept();
            dataInputStream = new DataInputStream(socket.getInputStream());
            getMessageFromClient();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void getMessageFromClient() {
        try {
            // 获取消息字节信息
            int length = dataInputStream.read();

            //获取消息
            byte[] body = new byte[length];
            String message = new String(body);

            System.out.println("客户端说：" + message);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TcpServerDemo server = new TcpServerDemo();
        server.startServer();
    }

}
